import { ElMessage, ElMessageBox } from 'element-plus';
import { useBrandApi } from '/@/api/brand';
import { deepCopy, descartes, arrHasData, isEmpty } from '/@/utils';
import { useProductApi } from '/@/api/product';
import { useInit } from '../list/hook';

const { init } = useInit();
const { addProd, editProd, getProdById, getGoodsTagList } = useProductApi();
const { getBrandList } = useBrandApi();

//根表单
export const rules = {
	name: { required: true, message: '请输入商品名称', trigger: 'blur' },
	standardCategoryId: { required: true, message: '请输入标准分类', trigger: 'blur' },
	// productCategoryId: { required: true, message: "请输入自定义分类", trigger: "blur" },
	brandId: { required: true, message: '请输入商品品牌', trigger: 'blur' },
	previewStatus: { required: true, message: '请选择是否预售', trigger: 'change' },
	tagId: { required: true, message: '请选择商品标签', trigger: 'blur' },
	keyword: { required: true, message: '请输入关键词', trigger: 'blur' },
};
//非表单字段
export const rulesSupplement = [
	{ key: 'albumPicsArr', type: 'array' },
	{ key: 'descriptionArr', type: 'array' },
	{ key: 'detailDesc', type: 'string' },
	{ key: 'specificationList', type: 'array' },
	{ key: 'specificationDetail', type: 'array' },
	{ key: 'skuStockList', type: 'skuStockList' },
];
//未填提示
export const requiredTip = {
	name: '商品名称',
	standardCategoryId: '标准分类',
	// productCategoryId: "自定义分类",
	brandId: '商品品牌',
	previewStatus: '是否预售',
	keyword: '关键词',
	albumPicsArr: '商品图片',
	descriptionArr: '产品概述',
	detailDesc: '产品详情',
	specificationList: '规格列表',
	specificationDetail: '规格明细',
	skuStockList: '规格设置',
};
// sku表单字段列表
export const skuListField = [
	// "attributeValue", //属性值，以逗号隔开
	'spData', //商品销售属性（规格），json格式
	'ukPrice', //英镑价格
	// "ukOriginalPrice", //英镑原价
	'usPrice', //美元价格
	// "usOriginalPrice", //美元原价
	'euPrice', //欧元价格
	// "euOriginalPrice", //欧元原价
	'costPrice', //成本价
	'stock', //库存
	// "skuCode", //sku编码
	// "skuId", //SKU ID
	'externalSku', //外部sku编码
	'supplierSku', //供应商sku编码
	'pic', //图片
];

export const useSaveProd = (proxy) => {
	const route = useRoute();
	const router = useRouter();
	console.log('00-----', route.name);
	const isAdd = route.name === 'ProductAddProduct';
	const ruleForm = ref({
		detailDesc: '',
		descriptionArr: [],
		framePic: '', //框架图
		dimensionList: [], //维度列表
		skuStockList: [],
		specificationList: [], //规格列表
		specificationDetail: [], //规格明细
		pdfUrl: '',
	});
	const formRef = ref();
	//const { loading: saveLoading, request: saveApi } = useApi(isAdd ? addProd : editProd);

	const saveProd = async () => {
		const { name, productCategoryFirstId, productCategorySecondId, productCategoryId, albumPicsArr, skuStockList, dimensionList } = ruleForm.value;
		if (isEmpty(name)) return ElMessage.warning('商品名称未填写，无法保存！');
		if (isEmpty(productCategoryFirstId) && isEmpty(productCategorySecondId) && isEmpty(productCategoryId))
			return ElMessage.warning('请选择商品自定义分类！');
		if (!arrHasData(albumPicsArr)) return ElMessage.warning('请至少添加一张商品图片！');
		if (!arrHasData(skuStockList)) return ElMessage.warning('商品规格列表不能为空！');
		if (!isValidDimensions(dimensionList)) return;

		//商品规格列表判空
		const hasEmptySku = ruleForm.value.skuStockList.some((item) => {
			//对需要必填的字段验证
			return skuListField.some((key) => {
				if (isEmpty(item[key])) {
					ElMessage.warning('商品规格列表存在未填写数据！');
					return true;
				}
			});
		});
		if (hasEmptySku) return;
		confirm();
		//提交[finish:是否编辑完成可以上架 1可以 0不可以]
		async function submit(finish) {
			ruleForm.value = typeTransition();
			let res;
			if (isAdd) {
				res = await addProd({ ...ruleForm.value, finish });
			} else {
				res = await editProd({ ...ruleForm.value, finish });
			}
			if (res.code !== 200) return;
			init();
			closeCurrentTagsView();
			ElMessage.success('保存成功！');
			//router.push({ name: 'ProductList' });
		}
		function typeTransition() {
			//主图
			const main = ruleForm.value.albumPicsArr.find((item) => item.isMain) || {};
			let pic = main.src || ruleForm.value.albumPicsArr[0].src;

			ruleForm.value.skuStockList.forEach((item) => {
				item.newStatus = ruleForm.value.newStatus;
			});
			return {
				...ruleForm.value,
				pic,
				albumPics: JSON.stringify(ruleForm.value.albumPicsArr),
				description: JSON.stringify(ruleForm.value.descriptionArr),
				spData: JSON.stringify(ruleForm.value.specificationDetail),
			};
		}
		//验证
		function confirm() {
			formRef.value.validate(async (valid, validObj) => {
				let keys = getUnvalidKeys(validObj || {});
				if (keys.length === 0) {
					submit(1);
				} else {
					ElMessageBox.confirm(`部分必要资料 [ ${getTipStr(keys)} ] 未填写，商品将无法上架，是否继续保存？`, '提示', {
						confirmButtonText: '确定保存',
						cancelButtonText: '继续补充',
						type: 'warning',
					})
						.then(async () => {
							submit(0);
						})
						.catch(() => {});
				}
			});
		}
		//获取验证未通过的字段
		function getUnvalidKeys(validObj) {
			const validKeys = Object.keys(validObj);
			const keys = [];
			//验证补充验证字段
			rulesSupplement.forEach(({ key, type }) => {
				let hasData;
				switch (type) {
					case 'array':
						hasData = arrHasData(ruleForm.value[key]);
						break;
					case 'string':
						hasData = !isEmpty(ruleForm.value[key]);
						break;
					case 'skuStockList':
						//sku列表验证（整个列表都是必填）
						if (!arrHasData(ruleForm.value[key])) break;
						hasData = true;
						ruleForm.value[key].some((item) => {
							//对需要必填的字段验证
							skuListField.some((key) => {
								if (isEmpty(item[key])) {
									hasData = false;
									return true;
								}
							});
							if (hasData === false) return true;
						});
						break;
					default:
						break;
				}
				if (!hasData) keys.push(key); //无数据存入数组，方便后续提示
			});
			return [...validKeys, ...keys];
		}
		//获取提示字符串
		function getTipStr(keys) {
			let str = '';
			keys.forEach((key, index) => {
				str = index === 0 ? requiredTip[key] : `${str}、${requiredTip[key]}`;
			});
			return str;
		}
		//验证商品维度是否存在未填字段
		function isValidDimensions(dimensionList) {
			let hasData = true;
			dimensionList.some((item1) => {
				item1.attrVoList.some((item2) => {
					if (isEmpty(item2.attrName) || isEmpty(item2.attrValue)) {
						hasData = false;
						return true;
					}
				});
				if (hasData === false) return true;
			});
			if (!hasData) ElMessage.warning('商品维度存在未填写的数据，请填写完整！');
			return hasData;
		}
	};

	// 关闭当然商品编辑tabs
	const closeCurrentTagsView = () => {
		let path = route.meta.isDynamicPath ? route.meta.isDynamicPath : route.path;
		proxy.mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, path, meta: route.meta }));
	};

	const cancel = () => {
		ElMessageBox.confirm(`将丢失未保存数据，是否继续退出编辑？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(async () => {
				//router.go(-1);
				closeCurrentTagsView();
			})
			.catch(() => {});
	};

	onMounted(() => {});
	return {
		ruleForm,
		formRef,
		saveProd,
		cancel,
		closeCurrentTagsView,
	};
};

export const useBrand = (ruleForm) => {
	const brandLoading = ref(false);
	const brandOptions = ref([]);
	const brandRemoteMethod = async (query) => {
		try {
			let params = {
				current: 1,
				pageSize: 999,
				name: query === ' ' ? null : query,
				status: 1, // 如果是null，表示查所有，是否展示 0->禁用；1->启用
			};
			brandLoading.value = true;
			let res = await getBrandList(params);
			brandLoading.value = false;
			if (res.code !== 200) return;
			brandOptions.value = res.data.data;
		} catch (error) {
			brandLoading.value = false;
			ElMessage.warning('网络错误，请稍后重试！');
		}
	};

	onMounted(() => {
		brandRemoteMethod(ruleForm.value.brandName || '');
	});

	return {
		brandLoading,
		brandOptions,
		brandRemoteMethod,
	};
};

export const useTags = () => {
	const tagsList = ref([]);
	const getTagsList = async () => {
		try {
			let params = {
				current: 1,
				pageSize: 999,
			};
			let res = await getGoodsTagList(params);
			if (res.code !== 200) return;
			tagsList.value = res.data.data;
		} catch (error) {
			ElMessage.warning('网络错误，请稍后重试！');
		}
	};

	onMounted(() => {
		getTagsList();
	});

	return {
		tagsList,
	};
};

export const useSpecification = (ruleForm) => {
	//更改规格多选框时
	function specificationListChange() {
		const specificationDetail = ruleForm.value.specificationDetail || [];
		ruleForm.value.specificationDetail = ruleForm.value.specificationList.map((item1) => {
			console.log(item1);
			//过滤已存在的规格：已存在直接返回，不存在则新增
			return (
				specificationDetail.find((item2) => {
					//有id比id，无id比name
					if (item1.id) {
						return item1.id === item2.id;
					} else {
						return item1.name === item2.name;
					}
				}) || deepCopy(item1)
			);
		});
		changeTagList();
	}
	//更改规格值时（tag）
	function changeTagList() {
		//变更数据为二维数组
		const specificationDetailArr = getSpecificationDetailArr();
		//判断规格明细表格是否有数据
		const hasData = specificationDetailArr.find((item) => item.length !== 0);
		if (!hasData) return;
		//使用笛卡尔积算法进行组合
		let specificationCombinationList = descartes(specificationDetailArr) || [];
		//循环二维数组-外层
		const skuStockList = specificationCombinationList.map((item1) => {
			return {
				skuAttributeValueList: item1, //包含该sku项的所有规格键与规格值的数组
				spData: getSpData(item1),
				ukPrice: 0,
				ukOriginalPrice: 0,
				usPrice: 0,
				usOriginalPrice: 0,
				euPrice: 0,
				euOriginalPrice: 0,
				costPrice: 0,
				stock: 0,
			};
		});
		ruleForm.value.skuStockList = skuStockList;
	}
	//修改规格值的值（tag中的值）
	function inputTag({ specificationName, oldValue, newValue }) {
		//外层-sku列表
		ruleForm.value.skuStockList.forEach((item1) => {
			//内层-规格值列表-设置列表的值
			item1.skuAttributeValueList.forEach((item2) => {
				if (!item2) return;
				if (item2.attributeName === specificationName && item2.attributeValue === oldValue) {
					item2.attributeValue = newValue;
				}
			});
			item1.spData = getSpData(item1.skuAttributeValueList);
		});
	}
	//新增规格值的值（tag）
	function addSpecificationValue() {
		//变更数据为二维数组
		const specificationDetailArr = getSpecificationDetailArr();
		//判断规格明细表格是否有数据
		const hasData = specificationDetailArr.find((item) => item.length !== 0);
		if (!hasData) return;
		//使用笛卡尔积算法进行组合
		let specificationCombinationList = descartes(specificationDetailArr) || [];
		//循环二维数组-外层
		const skuStockList = specificationCombinationList.map((item1) => {
			const spData = getSpData(item1);
			const data = ruleForm.value.skuStockList.find((item) => {
				return item.spData === spData;
			});
			if (data) {
				return data;
			} else {
				return {
					skuAttributeValueList: item1, //包含该sku项的所有规格键与规格值的数组
					spData,
					ukPrice: 0,
					ukOriginalPrice: 0,
					usPrice: 0,
					usOriginalPrice: 0,
					euPrice: 0,
					euOriginalPrice: 0,
					costPrice: 0,
					stock: 0,
				};
			}
		});
		ruleForm.value.skuStockList = skuStockList;
	}
	//删除规格值的值（tag）
	function delSpecificationValue({ specificationName, value }) {
		//外层-sku列表
		const skuStockList = ruleForm.value.skuStockList.filter((item1) => {
			let isDelItem = false;
			//内层-规格值列表-设置列表的值
			item1.skuAttributeValueList.forEach((item2) => {
				if (!item2) return;
				if (item2.attributeName === specificationName && item2.attributeValue === value) {
					isDelItem = true;
				}
			});
			return !isDelItem;
		});
		ruleForm.value.skuStockList = skuStockList;
	}
	//获取spData（格式为：规格值 * 规格值）
	function getSpData(skuAttributeValueList) {
		let spData = '';
		skuAttributeValueList.forEach((item, index) => {
			if (!item) return; //规格值为空时，该值为undefined
			//第一项不加连接符号“*”，往后加符号并连接后续数组
			spData += index === 0 ? item.attributeValue : ` * ${item.attributeValue}`;
		});
		return spData;
	}
	//变更数据(规格明细表格)为二维数组
	function getSpecificationDetailArr() {
		return ruleForm.value.specificationDetail.map((item1) => {
			if (item1.valueList) {
				const { id: attributeId, name: attributeName, valueList, ...data } = item1;
				return valueList.map(({ value }) => {
					return {
						...data,
						attributeId,
						attributeName,
						attributeValue: value,
					};
				});
			} else {
				return [];
			}
		});
	}
	return {
		specificationListChange,
		changeTagList,
		inputTag,
		addSpecificationValue,
		delSpecificationValue,
	};
};

export const useEditProd = (ruleForm) => {
	const route = useRoute();
	const id = Number(route.params.id);
	const editInit = async () => {
		let res = await getProdById(id);
		if (res.code !== 200) return;
		const { spData, albumPics, description, dimensionList, ...data } = res.data;
		let specificationList = [];
		const specificationDetail = JSON.parse(spData) || [];
		specificationDetail.forEach((item) => {
			specificationList.push({ name: item.name });
		});
		// for (const key in skuAttributeValueMap) {
		//     const valueList = skuAttributeValueMap[key].map((item: string) => {
		//         return { label: item, value: item };
		//     });
		//     specificationList.push({ name: key });
		//     specificationDetail.push({ name: key, valueList });
		// }
		ruleForm.value = {
			...data,
			albumPicsArr: JSON.parse(albumPics),
			descriptionArr: JSON.parse(description),
			specificationDetail,
			specificationList,
			dimensionList: dimensionList || [],
		};
	};
	if (id) onMounted(editInit);
	return {
		editInit,
	};
};
